#include "config_win32.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "spinlock.h"
#include "atomic.h"
//#include "skynet_daemon.h"
#include <pthread.h>
int daemon_init(const char* daemon)
{
		return 0;
}

int daemon_exit(const char* daemon)
{
		return 0;
}


void sleep(int sec)
{
	Sleep(sec * 1000);
}

void usleep(long usec)
{
	LARGE_INTEGER freq;
	LARGE_INTEGER start,end;
	QueryPerformanceFrequency(&freq);
	double count = usec * freq.QuadPart/(1000 * 1000);
	count = count + start.QuadPart;
	do
	{
		QueryPerformanceCounter(&end);
	}while(end.QuadPart < count);
}

void spinlock_init(struct spinlock* lock)
{
	pthread_mutex_init(&lock->lock,NULL);
}

void spinlock_lock(struct spinlock* lock)
{
	pthread_mutex_lock(&lock->lock);
}

int spinlock_trylock(struct spinlock* lock)
{
	return pthread_mutex_trylock(&lock->lock) ==0 ;
}

void spinlock_unlock(struct spinlock* lock)
{
	pthread_mutex_unlock(&lock->lock);
}
void spinlock_destroy(struct spinlock* lock)
{
	pthread_mutex_destroy(&lock->lock);
}

long ATOM_INC(long* ptr)
{
	return InterlockedIncrement(ptr);
}
long ATOM_FINC(long* ptr)
{
	long old = *ptr;
	InterlockedIncrement(ptr);
	return old;
}
long ATOM_DEC(long* ptr)
{
	return InterlockedDecrement(ptr);
}
long ATOM_FDEC(long* ptr)
{
	long old = *ptr;
	InterlockedDecrement(ptr);
	return old;
}
long ATOM_ADD(long* ptr,long n)
{
	return InterlockedExchangeAdd(ptr,n);
}

long ATOM_SUB(long* ptr,long n)
{
	return InterlockedExchangeAdd(ptr,-n);
}

long ATOM_CAS(long* ptr, long oval, long nval)
{
	*ptr = nval;
	return *ptr;
}
long ATOM_AND(long* ptr, LONG n)
{
	*ptr = *ptr & n;
	return *ptr;
}
void* dlopen(const char* dllname, int flag)
{
	HMODULE dllhandle = LoadLibrary(dllname);
	if (dllhandle)
	{
		return dllhandle;
	}
	return NULL;
}

void* dlsym(void* handle, const char* funcname)
{
	HMODULE module = (HMODULE)handle;
	return (void*)GetProcAddress(module, funcname);
}

const char* dlerror()
{
	static char buf[128];
	sprintf(buf, "last error=%d\n", GetLastError());
	return buf;
}

char* strsep(char** str,const char* delim)
{
	char* s;
	const char* sp;
	int c,sc;
	if((s =*str) == NULL)
		return NULL;
	char* tok;
	for(tok = s;;)
	{
		c = *s++;
		sp = delim;
		do {
			if((sc = *sp++) == c)
			{
				if(c ==0 )
					s= NULL;
				else
					s[-1] = 0;
				*str = s;
				return (tok);
			}
		}while(sc != 0);
	}
}